package org.jiangpeng.customer.controller;

import org.jiangpeng.customer.model.Customer;
import org.jiangpeng.customer.service.CustomerService;
import org.jiangpeng.customer.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户管理请求处理类
 *
 * @author jiangpeng
 */
@WebServlet(name = "CustomerServlet", urlPatterns = "/CustomerServlet")
public class CustomerServlet extends HttpServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerServlet.class);

    private CustomerService customerService = new CustomerService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String type = req.getParameter("type");
        LOGGER.debug("type:" + type);
        if (type != null && StringUtil.isNotEmpty(type)) {
            switch (type) {
                case "insert":
                    insertCustomer(req, resp);
                    break;
                case "insertPage":
                    req.getRequestDispatcher("WEB-INF/jsp/customer_create.jsp").forward(req,resp);
                    break;
                case "updatePage":
                    updatePageCustomer(req, resp);
                    break;
                case "update":
                    updateCustomer(req, resp);
                    break;
                case "delete":
                    deleteCustomer(req, resp);
                    break;
                default:
                    selectCustomer(req, resp);
                    break;
            }
        } else {
            selectCustomer(req, resp);
        }
    }

    /**
     * 添加客户的方法
     *
     * @param req
     * @param resp
     */
    private void insertCustomer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String msg = null;
        Map<String, Object> insertInfo = new HashMap<>();
        insertInfo.put("name", req.getParameter("name"));
        insertInfo.put("contact", req.getParameter("contact"));
        insertInfo.put("telephone", req.getParameter("telephone"));
        insertInfo.put("email", req.getParameter("email"));
        insertInfo.put("remake", req.getParameter("remake"));
        try {
            if(this.customerService.createCustomer(insertInfo)){
                resp.sendRedirect("/CustomerProject/CustomerServlet");
                return;
            }
            else{
                msg = "错误：客户修改失败！";
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(), e);
            msg = "错误：客户修改失败！错误原因：" + e.getMessage();
        }
        req.setAttribute("errorMsg", msg);
        req.getRequestDispatcher("WEB-INF/jsp/customer_error.jsp").forward(req,resp);
    }

    /**
     * 删除客户
     *
     * @param req
     * @param resp
     */
    private void deleteCustomer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String id = req.getParameter("id");
        String msg = null;
        if(id!= null && StringUtil.isNotEmpty(id)){
            try {
                if(this.customerService.deleteCustomer(Long.valueOf(id))){
                    resp.sendRedirect("/CustomerProject/CustomerServlet");
                    return;
                }
                else {
                    msg = "错误：删除客户信息失败！";
                }
            }
            catch (Exception e){
                LOGGER.error(e.getMessage(), e);
                msg = "错误：删除客户信息失败！错误原因：" + e.getMessage();
            }
        }
        req.setAttribute("errorMsg", msg);
        req.getRequestDispatcher("WEB-INF/jsp/customer_error.jsp").forward(req,resp);
    }

    /**
     * 客户修改界面
     * @param req
     * @param resp
     */
    private void updatePageCustomer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        if(id!= null && StringUtil.isNotEmpty(id)){
            req.setAttribute("Customer", this.customerService.getCustomer(Long.valueOf(id)));
            req.getRequestDispatcher("WEB-INF/jsp/customer_update.jsp").forward(req,resp);
        }
    }

    /**
     * 修改客户
     *
     * @param req
     * @param resp
     */
    private void updateCustomer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  {
        String id = req.getParameter("id");
        String msg = null;
        if (StringUtil.isNotEmpty(id)){
            Map<String, Object> updateInfo = new HashMap<>();
            updateInfo.put("name", req.getParameter("name"));
            updateInfo.put("contact", req.getParameter("contact"));
            updateInfo.put("telephone", req.getParameter("telephone"));
            updateInfo.put("email", req.getParameter("email"));
            updateInfo.put("remake", req.getParameter("remake"));
            try {
                if(this.customerService.updateCustomer(updateInfo, Long.valueOf(id))){
                    resp.sendRedirect("/CustomerProject/CustomerServlet");
                    return;
                }
                else{
                    msg = "错误：客户修改失败！";
                }
            }catch (Exception e){
                LOGGER.error(e.getMessage(), e);
                msg = "错误：客户修改失败！错误原因：" + e.getMessage();
            }
        }
        else{
            msg = "错误：客户修改失败！错误原因：id不能为空";
        }
        req.setAttribute("errorMsg", msg);
        req.getRequestDispatcher("WEB-INF/jsp/customer_error.jsp").forward(req,resp);
    }

    /**
     * 查询客户
     *
     * @param req
     * @param resp
     */
    private void selectCustomer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  {
        List<Customer> CustomerList = this.customerService.getCustomerList();
        LOGGER.debug("CustomerList.size():" + CustomerList.size());
        req.setAttribute("CustomerList", CustomerList);
        req.getRequestDispatcher("WEB-INF/jsp/customer_show.jsp").forward(req,resp);
        //resp.sendRedirect("WEB-INF/jsp/customer_show.jsp");
    }
}
